package cn.green.manage.service;

import cn.green.core.executor.DqlExecutor;
import cn.green.core.model.QTable;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wang.yishu
 * @version 1.0
 * @className QDqlService
 * @description 查询service
 * @date 2025/1/16 13:46
 */
public class QDqlService {

    public DqlExecutor dqlExecutor;

    public QDqlService(DqlExecutor dqlExecutor) {
        this.dqlExecutor = dqlExecutor;
    }


    public JSONArray simpleList(QTable table, JSONObject param) {
        return this.dqlExecutor.simpleList(table.getSourceName(), table.getSchemeName(), table.getTableName(), param);
    }

    public JSONArray list(QTable table, JSONObject param) {
        JSONArray select = this.dqlExecutor.select(table.getSourceName(), table.getSchemeName(), table.getTableName(), param);
        JSONArray data  = new JSONArray();
        for (int i = 0; i < select.size(); i++) {
            this.treeToList(data, select.getJSONObject(i));
        }
        return data;
    }

    public void treeToList(JSONArray data, JSONObject node) {
        JSONArray children = null;
        if (node.containsKey("children")) {
            children = node.getJSONArray("children");
            node.remove("children");
        }
        data.add(node);
        if (children != null) {
            for (int i = 0; i < children.size(); i++) {
                this.treeToList(data, children.getJSONObject(i));
            }
        }
    }

    /**
     * 查询列表
     * @param table     表信息
     * @param param     查询参数
     * @return  数据集
     */
    public JSONArray select(QTable table, JSONObject param) {
        return this.dqlExecutor.select(table.getSourceName(), table.getSchemeName(), table.getTableName(), param);
    }


    /**
     * 查询分页
     * @param table     表信息
     * @param param     查询参数
     * @return  数据集
     */
    public JSONObject page(QTable table, JSONObject param) {
        return this.dqlExecutor.page(table.getSourceName(), table.getSchemeName(), table.getTableName(), param.getIntValue("pageNo"), param.getIntValue("pageSize"), param);
    }

    /**
     * 查询明细
     * @param table     表信息
     * @param primaryKey 主键值
     * @return 数据
     */
    public JSONObject detail(QTable table, Object primaryKey) {
        return this.dqlExecutor.detail(table.getSourceName(), table.getSchemeName(), table.getTableName(), primaryKey);
    }

}
